<?php


namespace App\Services\CategoryGroup\Group;


use App\Models\Category;
use App\Services\CategoryGroup\BaseCategoryGroup;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class Subject extends BaseCategoryGroup
{
    /**
     * 添加分类
     *
     * @param Request $request
     * @return mixed|void
     */
    public function store(Request $request)
    {
        $request->validate($this->validate());

        parent::store($request);
    }

    public function validate()
    {
        switch (request()->method()) {
            case 'POST':
                return [
                    'name' => ['required', 'min:2', Rule::unique('categories', 'name')->where(function ($query) {
                        return $query->where('category_group_id', 1);
                    })],
                    'flag' => ['required', Rule::unique('categories', 'flag')->where(function ($query) {
                        return $query->where('category_group_id', 1);
                    })],
                    'pid' => ['bail', 'sometimes', 'required', 'exists:categories,id', function ($attr, $value, $fail) {
                        if (Category::find($value)->category_group_id != request()->input('category_group_id')) {
                            $fail('选择的上级分类并不在subject上');
                        }
                    }]
                ];
            case 'PUT':
            case 'PATCH':
                return [
                    'name' => ['required', 'min:2', Rule::unique('categories', 'name')->where(function ($query) {
                        return $query->where('category_group_id', 1);
                    })->ignore(request()->route()->parameter('category')->id)],
                    'flag' => ['required', Rule::unique('categories', 'flag')->where(function ($query) {
                        return $query->where('category_group_id', 1);
                    })->ignore(request()->route()->parameter('category')->id)],
                    'pid' => ['required', function ($attr, $value, $fail) {
                        if ($value != 0) {
                            if (!Category::where('id', $value)->exists()) {
                                $fail('pid 不存在');
                            }

                            if (Category::find($value)->category_group_id != request()->route()->parameter('category')->category_group_id) {
                                $fail('选择的上级分类并不在subject上');
                            }
                        }
                    }]
                ];
        }
    }

    public function update(Request $request, Category $category)
    {
        parent::update($request, $category);
    }
}
